var Config = require('../config').config;
var mysqlClient = require('mysql');


var dbExecuteSql = function (Sql, callback) {
  //  console.log(Config.blog) ;
    var conn = mysqlClient.createConnection(Config.blog) ;

    conn.connect();
    conn.query(Sql, function (err, result, fields) {
        if (err) {
           // console.log(err);
            conn.end();
            callback(err, undefined);
        }
        //conn.end();
        callback(undefined, result);
    });
};


exports.dbExecuteSql = dbExecuteSql;

var dbPageInfo = function (TableName, PageSize, Condition, callback) {
    var sql = "SELECT COUNT(*) Count FROM " + TableName + " WHERE ";
    sql = sql + (Condition == "" ? "1=1" : Condition);

    var conn = mysqlClient.createConnection(Config.blog);

    conn.connect();
    conn.query(sql, function (err, result, fields) {
        if (err) {
            console.log(err);
            conn.end();
            callback(err, undefined);
        }
        conn.end();

        var RecordCount = result[0].Count;

        var PageCount = Math.floor(result[0].Count / PageSize);

        if (RecordCount % PageSize > 0) {
            PageCount = PageCount + 1;
        }
        callback(undefined, PageCount);
    });

};

exports.dbPageInfo = dbPageInfo;

var dbPageData = function (Columns, TableName, CurrentPage, PageSize, Condition, OrderBy, callback) {
    var PageIndex = CurrentPage - 1;
    PageIndex = PageIndex * PageSize;

    var sql = "SELECT " + Columns + " FROM " + TableName + " WHERE ";
    sql = sql + (Condition == "" ? "1=1" : Condition);
    sql = sql + " ORDER BY " + OrderBy;
    sql = sql + " LIMIT " + PageIndex.toString() + "," + PageSize.toString();

    var conn = mysqlClient.createConnection(Config.blog);

    conn.connect();
    conn.query(sql, function (err, result, fields) {
        if (err) {
            console.log(err);
            conn.end();
            callback(err, undefined);
        }
        conn.end();
        callback(undefined, result);
    });

};

exports.dbPageData = dbPageData;
